// pages/store/franchis/index.js
const app = getApp()
const WXAPI = require('../../../miniprogram_npm/apifm-wxapi/index')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 表单数据
    formData: {
      storeName: '',
      linkPhone: '',
      type: '自营',
      address: '',
      serviceDistance: 5,
      openZiqu: true,
      openWaimai: true,
      openScan: true,
      expressType: 'dada',
      goodsNeedCheck: false,
      taxService: 0,
      taxGst: 0,
      cyTablePayMod: 1,
      // 图片相关
      storeCover: '', // 门店封面
      businessLicense: '', // 营业执照
      idCardFront: '', // 身份证正面
      idCardBack: '', // 身份证反面
      foodLicense: '', // 食品经营许可证
      healthCertificate: '', // 健康证
      storeEnvironment: [], // 店铺环境图片（多图）
      storeIntroduction: [] // 店铺介绍图片（多图）
    },
    
    // Vant uploader 文件列表
    storeCoverList: [],
    businessLicenseList: [],
    idCardFrontList: [],
    idCardBackList: [],
    foodLicenseList: [],
    healthCertificateList: [],
    storeEnvironmentList: [],
    storeIntroductionList: [],
    
    // 图片上传相关
    imageConfig: {
      maxSize: 5 * 1024 * 1024, // 5MB
      allowedTypes: ['jpg', 'jpeg', 'png', 'webp'],
      compressQuality: 0.8,
      maxMultipleImages: 9 // 多图上传最大数量
    },
    
    // 选择器数据
    typeOptions: ['自营', '加盟', '代理'],
    typeIndex: 0,
    
    expressOptions: [
      { value: 'dada', label: '达达配送' },
      { value: 'meituan', label: '美团配送' },
      { value: 'eleme', label: '饿了么配送' },
      { value: 'self', label: '自配送' }
    ],
    
    payModeOptions: [
      { value: 1, label: '微信支付' },
      { value: 2, label: '支付宝' },
      { value: 3, label: '现金支付' }
    ],
    payModeIndex: 0,
    
    // 地区选择
    region: ['江西省', '南昌市', '红谷滩区'],
    
    // 时间选择
    openTime: '00:00',
    closeTime: '23:59',
    
    // 位置信息
    latitude: 0,
    longitude: 0,
    locationText: '点击选择店铺位置',
    
    // 提交状态
    submitting: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: '加盟申请'
    })
    
    // 初始化表单数据
    this.initFormData()
  },

  /**
   * 初始化表单数据
   */
  initFormData() {
    // 可以从示例数据中预填充一些信息
    this.setData({
      'formData.storeName': '春熙路奶茶店',
      'formData.linkPhone': '13500000000',
      'formData.address': '绿茵路622号',
      'formData.serviceDistance': 5,
      latitude: 28.696372,
      longitude: 115.85834,
      locationText: '江西省南昌市红谷滩区'
    })
  },

  /**
   * 输入框变化处理
   */
  onInputChange(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    
    this.setData({
      [`formData.${field}`]: value
    })
  },

  /**
   * 滑块变化处理
   */
  onSliderChange(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    
    this.setData({
      [`formData.${field}`]: value
    })
  },

  /**
   * 开关变化处理
   */
  onSwitchChange(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    
    this.setData({
      [`formData.${field}`]: value
    })
  },

  /**
   * 复选框变化处理
   */
  onCheckboxChange(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    
    this.setData({
      [`formData.${field}`]: value.length > 0
    })
  },

  /**
   * 经营类型选择
   */
  onTypeChange(e) {
    const index = e.detail.value
    this.setData({
      typeIndex: index,
      'formData.type': this.data.typeOptions[index]
    })
  },

  /**
   * 配送方式选择
   */
  onExpressTypeChange(e) {
    this.setData({
      'formData.expressType': e.detail.value
    })
  },

  /**
   * 支付方式选择
   */
  onPayModeChange(e) {
    const index = e.detail.value
    this.setData({
      payModeIndex: index,
      'formData.cyTablePayMod': this.data.payModeOptions[index].value
    })
  },

  /**
   * 地区选择
   */
  onRegionChange(e) {
    this.setData({
      region: e.detail.value
    })
  },

  /**
   * 营业开始时间选择
   */
  onOpenTimeChange(e) {
    this.setData({
      openTime: e.detail.value
    })
  },

  /**
   * 营业结束时间选择
   */
  onCloseTimeChange(e) {
    this.setData({
      closeTime: e.detail.value
    })
  },

  /**
   * 选择位置
   */
  chooseLocation() {
    wx.chooseLocation({
      success: (res) => {
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          locationText: res.address || res.name,
          'formData.address': res.address || res.name
        })
      },
      fail: (err) => {
        if (err.errMsg.indexOf('cancel') === -1) {
          wx.showToast({
            title: '获取位置失败',
            icon: 'none'
          })
        }
      }
    })
  },

  /**
   * 文件大小超限处理
   */
  onOversize(e) {
    wx.showToast({
      title: '文件大小不能超过5MB',
      icon: 'none'
    })
  },

  /**
   * 使用提供的uploadFile函数上传文件
   */
  async uploadFileToServer(tempFilePath) {
    try {
      const token = wx.getStorageSync('token') || ''
      const result = await WXAPI.uploadFile(token, tempFilePath)
      if (result.code === 0) {
        return result.data.url
      } else {
        throw new Error(result.msg || '上传失败')
      }
    } catch (error) {
      console.error('上传失败:', error)
      wx.showToast({
        title: '上传失败',
        icon: 'none'
      })
      return null
    }
  },

  /**
   * 门店封面上传
   */
  async afterReadStoreCover(event) {
    const { file } = event.detail
    const fileList = Array.isArray(file) ? file : [file]
    
    wx.showLoading({ title: '上传中...' })
    
    for (let i = 0; i < fileList.length; i++) {
      const uploadedUrl = await this.uploadFileToServer(fileList[i].url)
      if (uploadedUrl) {
        fileList[i].url = uploadedUrl
        this.setData({
          'formData.storeCover': uploadedUrl,
          storeCoverList: [{ url: uploadedUrl, name: 'storeCover' }]
        })
      }
    }
    
    wx.hideLoading()
  },

  /**
   * 删除门店封面
   */
  deleteStoreCover(event) {
    this.setData({
      'formData.storeCover': '',
      storeCoverList: []
    })
  },

  /**
   * 营业执照上传
   */
  async afterReadBusinessLicense(event) {
    const { file } = event.detail
    const fileList = Array.isArray(file) ? file : [file]
    
    wx.showLoading({ title: '上传中...' })
    
    for (let i = 0; i < fileList.length; i++) {
      const uploadedUrl = await this.uploadFileToServer(fileList[i].url)
      if (uploadedUrl) {
        fileList[i].url = uploadedUrl
        this.setData({
          'formData.businessLicense': uploadedUrl,
          businessLicenseList: [{ url: uploadedUrl, name: 'businessLicense' }]
        })
      }
    }
    
    wx.hideLoading()
  },

  /**
   * 删除营业执照
   */
  deleteBusinessLicense(event) {
    this.setData({
      'formData.businessLicense': '',
      businessLicenseList: []
    })
  },

  /**
   * 身份证正面上传
   */
  async afterReadIdCardFront(event) {
    const { file } = event.detail
    const fileList = Array.isArray(file) ? file : [file]
    
    wx.showLoading({ title: '上传中...' })
    
    for (let i = 0; i < fileList.length; i++) {
      const uploadedUrl = await this.uploadFileToServer(fileList[i].url)
      if (uploadedUrl) {
        fileList[i].url = uploadedUrl
        this.setData({
          'formData.idCardFront': uploadedUrl,
          idCardFrontList: [{ url: uploadedUrl, name: 'idCardFront' }]
        })
      }
    }
    
    wx.hideLoading()
  },

  /**
   * 删除身份证正面
   */
  deleteIdCardFront(event) {
    this.setData({
      'formData.idCardFront': '',
      idCardFrontList: []
    })
  },

  /**
   * 身份证反面上传
   */
  async afterReadIdCardBack(event) {
    const { file } = event.detail
    const fileList = Array.isArray(file) ? file : [file]
    
    wx.showLoading({ title: '上传中...' })
    
    for (let i = 0; i < fileList.length; i++) {
      const uploadedUrl = await this.uploadFileToServer(fileList[i].url)
      if (uploadedUrl) {
        fileList[i].url = uploadedUrl
        this.setData({
          'formData.idCardBack': uploadedUrl,
          idCardBackList: [{ url: uploadedUrl, name: 'idCardBack' }]
        })
      }
    }
    
    wx.hideLoading()
  },

  /**
   * 删除身份证反面
   */
  deleteIdCardBack(event) {
    this.setData({
      'formData.idCardBack': '',
      idCardBackList: []
    })
  },

  /**
   * 食品经营许可证上传
   */
  async afterReadFoodLicense(event) {
    const { file } = event.detail
    const fileList = Array.isArray(file) ? file : [file]
    
    wx.showLoading({ title: '上传中...' })
    
    for (let i = 0; i < fileList.length; i++) {
      const uploadedUrl = await this.uploadFileToServer(fileList[i].url)
      if (uploadedUrl) {
        fileList[i].url = uploadedUrl
        this.setData({
          'formData.foodLicense': uploadedUrl,
          foodLicenseList: [{ url: uploadedUrl, name: 'foodLicense' }]
        })
      }
    }
    
    wx.hideLoading()
  },

  /**
   * 删除食品经营许可证
   */
  deleteFoodLicense(event) {
    this.setData({
      'formData.foodLicense': '',
      foodLicenseList: []
    })
  },

  /**
   * 健康证上传
   */
  async afterReadHealthCertificate(event) {
    const { file } = event.detail
    const fileList = Array.isArray(file) ? file : [file]
    
    wx.showLoading({ title: '上传中...' })
    
    for (let i = 0; i < fileList.length; i++) {
      const uploadedUrl = await this.uploadFileToServer(fileList[i].url)
      if (uploadedUrl) {
        fileList[i].url = uploadedUrl
        this.setData({
          'formData.healthCertificate': uploadedUrl,
          healthCertificateList: [{ url: uploadedUrl, name: 'healthCertificate' }]
        })
      }
    }
    
    wx.hideLoading()
  },

  /**
   * 删除健康证
   */
  deleteHealthCertificate(event) {
    this.setData({
      'formData.healthCertificate': '',
      healthCertificateList: []
    })
  },

  /**
   * 店铺环境图片上传
   */
  async afterReadStoreEnvironment(event) {
    const { file } = event.detail
    const fileList = Array.isArray(file) ? file : [file]
    
    wx.showLoading({ title: '上传中...' })
    
    const uploadedUrls = []
    const uploadedFiles = []
    
    for (let i = 0; i < fileList.length; i++) {
      const uploadedUrl = await this.uploadFileToServer(fileList[i].url)
      if (uploadedUrl) {
        uploadedUrls.push(uploadedUrl)
        uploadedFiles.push({ url: uploadedUrl, name: `storeEnvironment_${Date.now()}_${i}` })
      }
    }
    
    if (uploadedUrls.length > 0) {
      const currentImages = this.data.formData.storeEnvironment || []
      const currentFileList = this.data.storeEnvironmentList || []
      
      this.setData({
        'formData.storeEnvironment': [...currentImages, ...uploadedUrls],
        storeEnvironmentList: [...currentFileList, ...uploadedFiles]
      })
    }
    
    wx.hideLoading()
  },

  /**
   * 删除店铺环境图片
   */
  deleteStoreEnvironment(event) {
    const { index } = event.detail
    const currentImages = [...this.data.formData.storeEnvironment]
    const currentFileList = [...this.data.storeEnvironmentList]
    
    currentImages.splice(index, 1)
    currentFileList.splice(index, 1)
    
    this.setData({
      'formData.storeEnvironment': currentImages,
      storeEnvironmentList: currentFileList
    })
  },

  /**
   * 店铺介绍图片上传
   */
  async afterReadStoreIntroduction(event) {
    const { file } = event.detail
    const fileList = Array.isArray(file) ? file : [file]
    
    wx.showLoading({ title: '上传中...' })
    
    const uploadedUrls = []
    const uploadedFiles = []
    
    for (let i = 0; i < fileList.length; i++) {
      const uploadedUrl = await this.uploadFileToServer(fileList[i].url)
      if (uploadedUrl) {
        uploadedUrls.push(uploadedUrl)
        uploadedFiles.push({ url: uploadedUrl, name: `storeIntroduction_${Date.now()}_${i}` })
      }
    }
    
    if (uploadedUrls.length > 0) {
      const currentImages = this.data.formData.storeIntroduction || []
      const currentFileList = this.data.storeIntroductionList || []
      
      this.setData({
        'formData.storeIntroduction': [...currentImages, ...uploadedUrls],
        storeIntroductionList: [...currentFileList, ...uploadedFiles]
      })
    }
    
    wx.hideLoading()
  },

  /**
   * 删除店铺介绍图片
   */
  deleteStoreIntroduction(event) {
    const { index } = event.detail
    const currentImages = [...this.data.formData.storeIntroduction]
    const currentFileList = [...this.data.storeIntroductionList]
    
    currentImages.splice(index, 1)
    currentFileList.splice(index, 1)
    
    this.setData({
      'formData.storeIntroduction': currentImages,
      storeIntroductionList: currentFileList
    })
  },

  /**
   * 表单验证
   */
  validateForm() {
    const { formData, region } = this.data
    
    if (!formData.storeName.trim()) {
      wx.showToast({
        title: '请输入店铺名称',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.linkPhone.trim()) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      })
      return false
    }
    
    // 验证手机号格式
    const phoneReg = /^1[3-9]\d{9}$/
    if (!phoneReg.test(formData.linkPhone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.address.trim()) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      })
      return false
    }
    
    // 验证必需的图片上传
    if (!formData.storeCover) {
      wx.showToast({
        title: '请上传门店封面',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.businessLicense) {
      wx.showToast({
        title: '请上传营业执照',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.idCardFront) {
      wx.showToast({
        title: '请上传身份证正面',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.idCardBack) {
      wx.showToast({
        title: '请上传身份证反面',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.storeEnvironment || formData.storeEnvironment.length === 0) {
      wx.showToast({
        title: '请上传店铺环境图片',
        icon: 'none'
      })
      return false
    }
    
    return true
  },

  /**
   * 提交申请
   */
  submitApplication(e) {
    if (!this.validateForm()) {
      return
    }
    
    this.setData({
      submitting: true
    })
    
    // 构建提交数据
    const submitData = {
      ...this.data.formData,
      provinceId: this.getRegionId(this.data.region[0], 'province'),
      cityId: this.getRegionId(this.data.region[1], 'city'),
      districtId: this.getRegionId(this.data.region[2], 'district'),
      latitude: this.data.latitude,
      longitude: this.data.longitude,
      openingHours: `${this.data.openTime}-${this.data.closeTime}`,
      status: 0, // 待审核状态
      dateAdd: new Date().toISOString()
    }
    
    console.log('提交数据:', submitData)
    
    // 模拟提交请求
    setTimeout(() => {
      this.setData({
        submitting: false
      })
      
      wx.showModal({
        title: '申请提交成功',
        content: '您的加盟申请已提交，我们将在3个工作日内联系您，请保持电话畅通。',
        showCancel: false,
        success: () => {
          // 可以跳转到申请状态页面或返回上一页
          wx.navigateBack()
        }
      })
    }, 2000)
    
    // 实际项目中应该调用API
    // this.callSubmitAPI(submitData)
  },

  /**
   * 获取地区ID（示例方法，实际需要根据地区数据库获取）
   */
  getRegionId(regionName, type) {
    // 这里应该根据实际的地区数据库来获取ID
    // 示例返回值
    const regionIds = {
      '江西省': '360000000000',
      '南昌市': '360100000000',
      '红谷滩区': '360113000000'
    }
    return regionIds[regionName] || '000000000000'
  },

  /**
   * 调用提交API（示例方法）
   */
  callSubmitAPI(data) {
    // 实际项目中的API调用
    /*
    wx.request({
      url: 'https://your-api.com/franchise/apply',
      method: 'POST',
      data: data,
      success: (res) => {
        this.setData({
          submitting: false
        })
        
        if (res.data.success) {
          wx.showModal({
            title: '申请提交成功',
            content: '您的加盟申请已提交，我们将在3个工作日内联系您。',
            showCancel: false,
            success: () => {
              wx.navigateBack()
            }
          })
        } else {
          wx.showToast({
            title: res.data.message || '提交失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        this.setData({
          submitting: false
        })
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    })
    */
  },

  /**
   * 重置表单
   */
  resetForm() {
    wx.showModal({
      title: '确认重置',
      content: '确定要重置表单吗？所有填写的内容将被清空。',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            formData: {
              storeName: '',
              linkPhone: '',
              type: '自营',
              address: '',
              serviceDistance: 5,
              openZiqu: true,
              openWaimai: true,
              openScan: true,
              expressType: 'dada',
              goodsNeedCheck: false,
              taxService: 0,
              taxGst: 0,
              cyTablePayMod: 1
            },
            typeIndex: 0,
            payModeIndex: 0,
            region: ['江西省', '南昌市', '红谷滩区'],
            openTime: '00:00',
            closeTime: '23:59',
            latitude: 0,
            longitude: 0,
            locationText: '点击选择店铺位置'
          })
          
          wx.showToast({
            title: '表单已重置',
            icon: 'success'
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '加盟申请 - 开启您的创业之路',
      path: '/pages/store/franchis/index'
    }
  }
})